<template>
	<SlotModal ref='slotModalRef' v-bind='slotModalConfig'>
		<n-form ref='formRef' v-bind='formConfig'
				:model='formData' :rules='formRules'>
			<n-grid :x-gap='24' :cols='2'>
				<n-form-item-grid-item label='策略编码' path='strategyCode'>
					<n-input v-model:value='formData.strategyCode' type='text'
							 disabled readonly/>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='策略名称' path='strategyName'>
					<n-input v-model:value='formData.strategyName' type='text' clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='租户过期时间' path='tenantExpireTime'>
					<n-date-picker v-model:formatted-value='formData.tenantExpireTime' type='datetime'
								   format='yyyy-MM-dd HH:mm:ss' value-format='yyyy-MM-dd HH:mm:ss'
								   clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='token签发时长' path='tokenExpireTime'>
					<n-tooltip trigger='click'>
						<template v-slot:trigger>
							<n-input-number v-model:value='formData.tokenExpireTime' style='width:100%;'
											min='1800' max='86400' clearable/>
						</template>
						单位为秒,最小1800秒(30分钟),最长86400秒(24小时)
					</n-tooltip>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='登录有效时间' path='loginActiveTime'>
					<n-tooltip trigger='click'>
						<template v-slot:trigger>
							<n-input-number v-model:value='formData.loginActiveTime' style='width:100%;'
											min='1800' max='86400' clearable/>
						</template>
						单位为秒,最小1800秒(30分钟),最长86400秒(24小时)
					</n-tooltip>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='账号数量' path='accountCount'>
					<n-tooltip trigger='click'>
						<template v-slot:trigger>
							<n-input-number v-model:value='formData.accountCount'
											style='width:100%;' :min='-1' clearable/>
						</template>
						单位为个,-1为无限制
					</n-tooltip>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='序号' path='sort'>
					<n-input-number v-model:value='formData.sort'
									style='width:100%;' min='0' clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item label='是否启用' path='status'>
					<n-switch v-model:value='formData.status as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='2' label='备注' path='remark'>
					<n-input v-model:value='formData.remark'
							 type='textarea' placeholder='请输入备注,没有可留空'
							 :autosize='{minRows:3,maxRows:3}' clearable
							 maxlength='200' show-word-count/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='2'>
					<n-flex justify='center' style='width:100%;'>
						<n-button type='primary' @click='submitEvent'>
							提交
						</n-button>
						<n-button type='info' @click='clearFormData'>
							重置
						</n-button>
					</n-flex>
				</n-form-item-grid-item>
			</n-grid>
		</n-form>
	</SlotModal>
</template>
<script lang='ts' setup>
import { defineAsyncComponent, reactive, ref } from 'vue';
// axios
import axios from '@/config/axios/index.ts';
// 模态框和打印组件
import { VxeUI } from '@/config/vxe/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import type { SysStrategyProps } from '#/SysStrategy.d.ts';
import { FormInst, FormProps, FormRules, FormValidationError } from 'naive-ui';
// ------------------------------------------------------------------------------------
const SlotModal = defineAsyncComponent(() => import('@/components/customComponents/modal/SlotModal.vue'));
// ------------------------------------------------------------------------------------
// 接收的参数
const props = defineProps({
	params : {
		type    : Object,
		require : false,
		default : null
	},
	reLoad : {
		type    : Function,
		require : true,
		default : null
	}
});
// ------------------------------------------------------------------------------------
// 模态框的配置
const slotModalConfig = reactive({
	reLoad            : () => props.reLoad(),
	onCloseModalEvent : () => clearFormData(),
	resetEvent        : () => clearFormData()
});
// 表单配置
const formConfig = reactive<FormProps>({
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	size                 : 'medium',
	requireMarkPlacement : 'right-hanging'
});
// ------------------------------------------------------------------------------------
const currentData = reactive<Partial<SysStrategyProps>>({});
// 表单绑定数据
const formData = reactive<Partial<SysStrategyProps>>({});
// 表单校验规则
const formRules = reactive<FormRules>({
	sort             : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '请输入序号'
	},
	strategyCode     : {
		required : true,
		type     : 'string',
		trigger  : ['input', 'blur'],
		message  : '请输入策略编码'
	},
	strategyName     : {
		required : true,
		type     : 'string',
		trigger  : ['input', 'blur'],
		message  : '请输入策略名称'
	},
	tenantExpireTime : {
		required : true,
		type     : 'date',
		trigger  : ['input', 'blur'],
		message  : '请选择租户过期时间'
	},
	tokenExpireTime  : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '请输入token签发时长'
	},
	loginActiveTime  : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '请输入登录有效时间'
	},
	accountCount     : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '请输入账号数量'
	},
	status           : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '请选择是否启用'
	}
});
// ------------------------------------------------------------------------------------
const slotModalRef = ref<InstanceType<typeof SlotModal>>();
const formRef = ref<FormInst>();
// ------------------------------------------------------------------------------------
const refresh = async () => {
	axios<any, JsonResultProps<any>, any>({
		method : 'GET',
		url    : `/strategy/detail/${currentData.strategyCode}`
	}).then((jsonResult: JsonResultProps<any>) => {
		if (jsonResult.status) {
			// 数据填充
			Object.assign(formData, jsonResult.data);
		} else {
			VxeUI.modal.message({
				content : jsonResult.msg,
				status  : 'warning',
				id      : 'failedMessage'
			});
		}
	}).catch((error: unknown) => {
		console.error(error);
		VxeUI.modal.message({
			content : '系统异常,请稍后再试',
			status  : 'error',
			id      : 'errorMessage'
		});
	});
};
const showModal = async (rowData: SysStrategyProps) => {
	Object.assign(currentData, rowData);
	await slotModalRef.value!.openModal({
		height     : '500',
		width      : '700',
		title      : '编辑',
		showClose  : true,
		showZoom   : true,
		fullscreen : false
	});
};
const clearFormData = async () => {
	// 清理表单数据
	Object.assign(formData, {
		strategyCode     : null,
		strategyName     : null,
		tenantExpireTime : null,
		tokenExpireTime  : null,
		loginActiveTime  : null,
		accountCount     : -1,
		status           : true,
		remark           : null,
		sort             : null
	});
	// 去除表单校验提示
	formRef.value?.restoreValidation();
	await refresh();
};
const submitEvent = async () => {
	// 校验菜单
	formRef.value?.validate((errors?: Array<FormValidationError>): void => {
		if (errors) {
			VxeUI.modal.message({ content : '请先完善填写的内容!', status : 'warning', id : 'validateMessage' });
		} else {
			// 提交数据
			axios<any, JsonResultProps<any>, any>({
				method : 'PUT',
				url    : '/strategy/modify',
				data   : formData
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult.status) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult.msg,
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					props.reLoad();
					slotModalRef.value!.closeModal();
				} else {
					VxeUI.modal.message({
						content : jsonResult.msg,
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
// 导出方法
defineExpose({ showModal });
</script>